package com.cdd.edumsm.controller;

import com.cdd.commonutils.R;
import com.cdd.edumsm.service.MsmService;
import com.cdd.edumsm.utils.RandomUtil;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //邮箱验证码
    @GetMapping("send/{emailaddress}")
    public R sendEmail(@PathVariable String emailaddress) {
        // 1.先从redis里取验证码
        String code = redisTemplate.opsForValue().get(emailaddress);
        if(!StringUtils.isEmpty(code)) return R.ok();
        // 2.redis中没有验证码
        if(StringUtils.isEmpty(emailaddress)) return R.error().data("message","邮箱不能为空！");
        code = RandomUtil.getFourBitRandom();
        Map<String, Object> param = new HashMap<>();
        param.put("code",code);
        boolean isSend = msmService.send(emailaddress,param);
        if(isSend) {
            // 发送成功
            redisTemplate.opsForValue().set(emailaddress,code,5, TimeUnit.MINUTES); // 设置验证码5分钟有效
            return R.ok();
        } else {
            return R.error();
        }



    }
}
